package com.jeff.cloud.consumermovie.feign;

import com.jeff.cloud.consumermovie.bean.User;
import feign.hystrix.FallbackFactory;
import org.omg.CORBA.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 本例中使用了eureka,Ribbon会把"microservice-provider-user"解析成Eureka服务注册表中的服务。
 * 如果不想使用eureka，可以yml使用service.ribbon.listOfServers属性配置服务器列表.
 * 结果看来，不但实现了声明式的RestApi调用，同时还实现了客户端侧的负载均衡。
 * 2021/8/10 17:24
 * @author: jeff
 * @date: 2021/8/9 14:36
 */
@FeignClient(name="microservice-provider-user",fallbackFactory = FeignClientFallbackFactory.class)
public interface UserFeignClient {
    @RequestMapping(value="/{id}",method = RequestMethod.GET)
    public User findById(@PathVariable("id") Long id);
}

/*
 * UserFeignClient的fallbackFactory类，该类需实现FallbackFactory接口，并覆盖create方法。
 * @return:
 * @author: jeff
 * @date: 2021/8/10 17:24
 */
@Component
class FeignClientFallbackFactory implements FallbackFactory<UserFeignClient>{
    private static final Logger LOGGER = LoggerFactory.getLogger(FeignClientFallbackFactory.class);
    @Override
    public UserFeignClient create(final Throwable throwable) {
        return new UserFeignClient() {
            @Override
            public User findById(Long id) {
                //日志最好放在各个fallback方法中，而不要直接放在create方法中。
                //否则在引用启动时，就会打印该日志.
                FeignClientFallbackFactory.LOGGER.info("fallback;reason was:",throwable);
                User user = new User();
                if (throwable instanceof IllegalArgumentException){
                    user.setName("默认2");
                }else{
                    user.setName("默认1");
                }
                user.setId(id<0?id:-1);
                user.setUsername("默认用户");
                return user;
            }
        };
    }
}